<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Spring 源码学习 16：单例 Bean 创建 | 程序员小航</title><meta name="keywords" content="Spring,源码笔记"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="在 finishBeanFactoryInitialization 中介绍了创建 Bean 的流程大概流程，这里进入单例 Bean 的创建过程。">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring 源码学习 16：单例 Bean 创建">
<meta property="og:url" content="https://liuzhihang.com/2021/01/17/source-spring-16.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="在 finishBeanFactoryInitialization 中介绍了创建 Bean 的流程大概流程，这里进入单例 Bean 的创建过程。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/fybVmp-2dcCmU.png">
<meta property="article:published_time" content="2021-01-17T13:40:00.000Z">
<meta property="article:modified_time" content="2021-01-18T08:19:22.468Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="Spring">
<meta property="article:tag" content="源码笔记">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/fybVmp-2dcCmU.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2021/01/17/source-spring-16"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Spring 源码学习 16：单例 Bean 创建',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-01-18 16:19:22'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/fybVmp-2dcCmU.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Spring 源码学习 16：单例 Bean 创建</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-01-17T13:40:00.000Z" title="发表于 2021-01-17 21:40:00">2021-01-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-01-18T08:19:22.468Z" title="更新于 2021-01-18 16:19:22">2021-01-18</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/Spring/">Spring</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.3k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>10分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Spring 源码学习 16：单例 Bean 创建"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2021/01/17/source-spring-16.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h3><p>在 finishBeanFactoryInitialization 中介绍了创建 Bean 的流程大概流程，这里进入单例 Bean 的创建过程。</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/U1LzL3-cy2ZtW.png"></p>
<p>这里主要分为三个部分创建单例 Bean</p>
<ol>
<li>getSingleton</li>
<li>createBean</li>
<li>getObjectForBeanInstance</li>
</ol>
<p>下面进入源码：</p>
<h3 id="getSingleton"><a href="#getSingleton" class="headerlink" title="getSingleton"></a>getSingleton</h3><pre><code class="java">public Object getSingleton(String beanName, ObjectFactory&lt;?&gt; singletonFactory) &#123;
    Assert.notNull(beanName, &quot;Bean name must not be null&quot;);
    // 加锁
    synchronized (this.singletonObjects) &#123;
        // 检查 singletonObjects 缓存中是否有
        Object singletonObject = this.singletonObjects.get(beanName);
        if (singletonObject == null) &#123;
            // 检查是否在执行销毁
            if (this.singletonsCurrentlyInDestruction) &#123;
                throw new BeanCreationNotAllowedException(beanName,
                        &quot;Singleton bean creation not allowed while singletons of this factory are in destruction &quot; +
                        &quot;(Do not request a bean from a BeanFactory in a destroy method implementation!)&quot;);
            &#125;
            if (logger.isDebugEnabled()) &#123;
                logger.debug(&quot;Creating shared instance of singleton bean &#39;&quot; + beanName + &quot;&#39;&quot;);
            &#125;
            // 将 Bean 添加到 singletonsCurrentlyInCreation 集合中, 表示正在创建
            beforeSingletonCreation(beanName);
            boolean newSingleton = false;
            boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
            if (recordSuppressedExceptions) &#123;
                this.suppressedExceptions = new LinkedHashSet&lt;&gt;();
            &#125;
            try &#123;
                // 调用工厂方法
                // 也就是调用 createBean(beanName, mbd, args)
                singletonObject = singletonFactory.getObject();
                newSingleton = true;
            &#125;
            catch (IllegalStateException ex) &#123;
                // Has the singleton object implicitly appeared in the meantime -&gt;
                // if yes, proceed with it since the exception indicates that state.
                singletonObject = this.singletonObjects.get(beanName);
                if (singletonObject == null) &#123;
                    throw ex;
                &#125;
            &#125;
            catch (BeanCreationException ex) &#123;
                if (recordSuppressedExceptions) &#123;
                    for (Exception suppressedException : this.suppressedExceptions) &#123;
                        ex.addRelatedCause(suppressedException);
                    &#125;
                &#125;
                throw ex;
            &#125;
            finally &#123;
                if (recordSuppressedExceptions) &#123;
                    this.suppressedExceptions = null;
                &#125;
                // 创建成功, 从 singletonsCurrentlyInCreation 移除
                afterSingletonCreation(beanName);
            &#125;
            if (newSingleton) &#123;
                // 将给定的单例对象添加到该工厂的单例缓存中
                //     this.singletonObjects.put(beanName, singletonObject);
                //     this.singletonFactories.remove(beanName);
                //     this.earlySingletonObjects.remove(beanName);
                //     this.registeredSingletons.add(beanName);
                addSingleton(beanName, singletonObject);
            &#125;
        &#125;
        return singletonObject;
    &#125;
&#125;</code></pre>
<p>返回以给定名称注册的（原始）单例对象，如果尚未注册，则创建并注册一个新对象。</p>
<p>这一块一共可以拆成三部分来理解：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/6KBL1X-ZvNhzi.png"></p>
<h4 id="1-从缓存中获取-singletonObjects"><a href="#1-从缓存中获取-singletonObjects" class="headerlink" title="1. 从缓存中获取 singletonObjects"></a>1. 从缓存中获取 singletonObjects</h4><p><code>singletonObject</code> 是什么？</p>
<pre><code class="java">/** Cache of singleton objects: bean name to bean instance. */
private final Map&lt;String, Object&gt; singletonObjects = new ConcurrentHashMap&lt;&gt;(256);</code></pre>
<p><code>singletonObjects</code> 是一个 ConcurrentHashMap， 用来缓存单例对象的实例。</p>
<h4 id="2-创建-singletonObject"><a href="#2-创建-singletonObject" class="headerlink" title="2. 创建 singletonObject"></a>2. 创建 singletonObject</h4><p>在从缓存中没有获取到 <code>singletonObject</code> ，创建新的对象</p>
<p><code>singletonObject = singletonFactory.getObject();</code> </p>
<p>这一步其实就是调用外边的 <code>createBean(beanName, mbd, args)</code> 方法，这是一个工厂方法。 通过 <code>createBean</code> 方法，会创建一个新的 <code>singletonObject</code>。</p>
<h4 id="3-将创建的-singletonObject-添加到缓存中"><a href="#3-将创建的-singletonObject-添加到缓存中" class="headerlink" title="3. 将创建的 singletonObject 添加到缓存中"></a>3. 将创建的 singletonObject 添加到缓存中</h4><pre><code class="java">protected void addSingleton(String beanName, Object singletonObject) &#123;
    synchronized (this.singletonObjects) &#123;
        this.singletonObjects.put(beanName, singletonObject);
        this.singletonFactories.remove(beanName);
        this.earlySingletonObjects.remove(beanName);
        // 已经成功创建的单例
        this.registeredSingletons.add(beanName);
    &#125;
&#125;</code></pre>
<p>这一步涉及到三个缓存，以及一个成功创建的单例列表。</p>
<pre><code class="java">/** Cache of singleton objects: bean name to bean instance. */
/** 缓存单例对象， K-V -&gt; BeanName - Bean 实例 */
private final Map&lt;String, Object&gt; singletonObjects = new ConcurrentHashMap&lt;&gt;(256);

/** Cache of singleton factories: bean name to ObjectFactory. */
/** 缓存 Bean 工厂 */
private final Map&lt;String, ObjectFactory&lt;?&gt;&gt; singletonFactories = new HashMap&lt;&gt;(16);

/** Cache of early singleton objects: bean name to bean instance. */
/** 缓存早期单例对象 */
private final Map&lt;String, Object&gt; earlySingletonObjects = new ConcurrentHashMap&lt;&gt;(16);

/** Set of registered singletons, containing the bean names in registration order. */
/** 已注册的单例列表，按注册顺序保存 BeanName。 */
private final Set&lt;String&gt; registeredSingletons = new LinkedHashSet&lt;&gt;(256);</code></pre>
<p>将创建的单例对象，添加到<code>单例缓存</code>中，同时将<code>工厂缓存</code>以及<code>早期单例对象缓存</code>中的对应对象删除。</p>
<h3 id="createBean"><a href="#createBean" class="headerlink" title="createBean"></a>createBean</h3><pre><code class="java">protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException &#123;

    if (logger.isTraceEnabled()) &#123;
        logger.trace(&quot;Creating instance of bean &#39;&quot; + beanName + &quot;&#39;&quot;);
    &#125;
    RootBeanDefinition mbdToUse = mbd;

    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    // 获取真实的类型
    Class&lt;?&gt; resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null &amp;&amp; !mbd.hasBeanClass() &amp;&amp; mbd.getBeanClassName() != null) &#123;
        // 创建新的 mbd 防止 其他线程修改
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    &#125;

    // Prepare method overrides.
    try &#123;
        // 验证并准备为此bean定义的方法替代。 检查是否存在具有指定名称的方法。
        mbdToUse.prepareMethodOverrides();
    &#125;
    catch (BeanDefinitionValidationException ex) &#123;
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, &quot;Validation of method overrides failed&quot;, ex);
    &#125;

    try &#123;
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        // 应用实例化之前的后处理器，以解决指定的bean是否存在实例化快捷方式。
        // InstantiationAwareBeanPostProcessor 后置处理器 
        // postProcessBeforeInstantiation 方法可能会已经实例化 Bean
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) &#123;
            return bean;
        &#125;
    &#125;
    catch (Throwable ex) &#123;
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                &quot;BeanPostProcessor before instantiation of bean failed&quot;, ex);
    &#125;

    try &#123;
        // 实例化 Bean
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isTraceEnabled()) &#123;
            logger.trace(&quot;Finished creating instance of bean &#39;&quot; + beanName + &quot;&#39;&quot;);
        &#125;
        return beanInstance;
    &#125;
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) &#123;
        // A previously detected exception with proper bean creation context already,
        // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
        throw ex;
    &#125;
    catch (Throwable ex) &#123;
        throw new BeanCreationException(
                mbdToUse.getResourceDescription(), beanName, &quot;Unexpected exception during bean creation&quot;, ex);
    &#125;
&#125;</code></pre>
<p>这个方法中涉及到：创建 Bean 实例 , 填充 Bean , 应用 PostProcessor。</p>
<p>其中实例化 Bean 是在 <code>doCreateBean</code> 中。现在重点看一下 <code>doCreateBean</code> 方法。</p>
<h4 id="doCreateBean"><a href="#doCreateBean" class="headerlink" title="doCreateBean"></a>doCreateBean</h4><pre><code class="java">protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException &#123;

    // Instantiate the bean.
    // Bean 的 对象包装
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) &#123;
        // 从缓存中获取
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    &#125;
    if (instanceWrapper == null) &#123;
        // 缓存中获取不到则直接创建, 这里创建的 BeanInstance !!!
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    &#125;
    // 获取 Bean 实例以及类型
    Object bean = instanceWrapper.getWrappedInstance();
    Class&lt;?&gt; beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) &#123;
        mbd.resolvedTargetType = beanType;
    &#125;

    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) &#123;
        if (!mbd.postProcessed) &#123;
            try &#123;
                // 如果允许修改 mbd
                // 调用 MergedBeanDefinitionPostProcessor 后置处理器的
                // postProcessMergedBeanDefinition(mbd, beanType, beanName);
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            &#125;
            catch (Throwable ex) &#123;
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        &quot;Post-processing of merged bean definition failed&quot;, ex);
            &#125;
            mbd.postProcessed = true;
        &#125;
    &#125;

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    // mbd 是单例 且 允许循环引用, (默认 true) 且在创建
    boolean earlySingletonExposure = (mbd.isSingleton() &amp;&amp; this.allowCircularReferences &amp;&amp;
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) &#123;
        if (logger.isTraceEnabled()) &#123;
            logger.trace(&quot;Eagerly caching bean &#39;&quot; + beanName +
                    &quot;&#39; to allow for resolving potential circular references&quot;);
        &#125;
        // 先获取 之前的 Bean 的引用, 从 beanPostProcessorCache 中 获取 SmartInstantiationAwareBeanPostProcessor
        // 然后从 SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference 获取之前的引用
        addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean));
    &#125;

    // Initialize the bean instance.
    Object exposedObject = bean;
    try &#123;
        // 属性赋值
        populateBean(beanName, mbd, instanceWrapper);
        // 执行 init 方法
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    &#125;
    catch (Throwable ex) &#123;
        if (ex instanceof BeanCreationException &amp;&amp; beanName.equals(((BeanCreationException) ex).getBeanName())) &#123;
            throw (BeanCreationException) ex;
        &#125;
        else &#123;
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, &quot;Initialization of bean failed&quot;, ex);
        &#125;
    &#125;

    // 这里允许循环依赖
    if (earlySingletonExposure) &#123;
        // 获取早期的 Bean, 如果没有循环依赖 则获取不到
        Object earlySingletonReference = getSingleton(beanName, false);

        // 有循环依赖
        if (earlySingletonReference != null) &#123;
            // 创建的是不是同一个，可能会有代理对象
            if (exposedObject == bean) &#123;
                exposedObject = earlySingletonReference;
            &#125;
            else if (!this.allowRawInjectionDespiteWrapping &amp;&amp; hasDependentBean(beanName)) &#123;
                // 获取依赖的 Bean 并 循环放入到 actualDependentBeans
                String[] dependentBeans = getDependentBeans(beanName);
                Set&lt;String&gt; actualDependentBeans = new LinkedHashSet&lt;&gt;(dependentBeans.length);
                for (String dependentBean : dependentBeans) &#123;
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) &#123;
                        actualDependentBeans.add(dependentBean);
                    &#125;
                &#125;
                if (!actualDependentBeans.isEmpty()) &#123;
                    throw new BeanCurrentlyInCreationException(beanName,
                            &quot;Bean with name &#39;&quot; + beanName + &quot;&#39; has been injected into other beans [&quot; +
                            StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                            &quot;] in its raw version as part of a circular reference, but has eventually been &quot; +
                            &quot;wrapped. This means that said other beans do not use the final version of the &quot; +
                            &quot;bean. This is often the result of over-eager type matching - consider using &quot; +
                            &quot;&#39;getBeanNamesForType&#39; with the &#39;allowEagerInit&#39; flag turned off, for example.&quot;);
                &#125;
            &#125;
        &#125;
    &#125;

    // Register bean as disposable.
    try &#123;
        // 注册销毁方法
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    &#125;
    catch (BeanDefinitionValidationException ex) &#123;
        throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, &quot;Invalid destruction signature&quot;, ex);
    &#125;

    return exposedObject;
&#125;</code></pre>
<p>同样是代码很长很长！</p>
<p>分步骤阅读：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/tx0C4e-zD6xG0.png"></p>
<p>如果这个 Bean 是单例 Bean 且允许循环引用且在创建中，则说明在有循环引用。则调用：</p>
<p><code>addSingletonFactory(beanName, () -&gt; getEarlyBeanReference(beanName, mbd, bean));</code></p>
<p>这一行代码涉及到两个方法，分别是 <code>getEarlyBeanReference</code> 和 <code>addSingletonFactory</code></p>
<ul>
<li>getEarlyBeanReference</li>
</ul>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/vWP5Jt-tsa92g.png"></p>
<ul>
<li>addSingletonFactory</li>
</ul>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uvUVh4-TWy5l0.png"></p>
<p>这一块可以看到将创建的一个单例对象的 <code>singletonFactory</code> 添加到了 <code>singletonFactories</code> 缓存中。</p>
<p>同时将 <code>earlySingletonObjects</code> 缓存中的单例对象移除。</p>
<p>那什么时候添加到 <code>earlySingletonObjects</code> 缓存中的呢？</p>
<p>这块可以参考 <a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/MAlT1Y5MVmEclAZC6rgojQ">Spring 源码学习 15：finishBeanFactoryInitialization</a> 在 <code>getSingleton</code> 方法中 put 进去的。</p>
<p>为了方便，我把这一小块代码也贴出来：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/QPVvXy-pJUe1N.png"></p>
<p>在这里将缓存从 <code>singletonFactories</code> 移到了 <code>earlySingletonObjects</code>。</p>
<p>Spring 的 Bean 实例化的时候用到的三级缓存其实是：</p>
<p><strong>singletonObjects：</strong> 一级缓存，存储单例对象，Bean 已经实例化，初始化完成。</p>
<p><strong>earlySingletonObjects：</strong> 二级缓存，存储 singletonObject，这个 Bean 实例化了，还没有初始化。 </p>
<p><strong>singletonFactories：</strong> 三级缓存，存储 singletonFactory</p>
<p><strong>下面会初始化 Bean</strong></p>
<p>这里关注重点关注下面一部分：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/hmZmhM-SI303W.png"></p>
<ul>
<li>populateBean</li>
</ul>
<p>对 Bean 的属性进行赋值。</p>
<p>这块需要注意的是，在对属性进行赋值时，发现依赖了其他 Bean，就会去先创建其他 Bean。</p>
<p>我这边使用的注解 @Autowired 就会执行下面一部分：</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ZjKmVC-J3xIl5.png"></p>
<p>在这里解析属性的时候，就会去创建内部依赖的 Bean。</p>
<ul>
<li>initializeBean</li>
</ul>
<h3 id="getObjectForBeanInstance"><a href="#getObjectForBeanInstance" class="headerlink" title="getObjectForBeanInstance"></a>getObjectForBeanInstance</h3><p>获取给定bean实例的对象，如果是FactoryBean，则为bean实例本身或其创建的对象。</p>
<p>这一块逻辑相对比较简单，就是根据前面你创建的 beanInstance ， 判断其类型，从而创建 Bean 实例。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>本文主要介绍了一个 单例 Bean 的创建，当然都是大块大块的源码，需要耐心的啃。</p>
<p>阅读完源码，基本上对循环依赖能有个详细的了解，知道 Spring 在初始化 Bean 的时候是使用三级缓存来处理循环依赖的额，而后面则会单独准备一篇文章对循环依赖做介绍。</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/fybVmp-2dcCmU.png"></p>
<h4 id="相关推荐"><a href="#相关推荐" class="headerlink" title="相关推荐"></a>相关推荐</h4><ul>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/MAlT1Y5MVmEclAZC6rgojQ">Spring 源码学习 15：finishBeanFactoryInitialization（重点）</a></li>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/bKmqVFuLLLCquWf3tzH30g">Spring 源码学习 14：initApplicationEventMulticaster</a></li>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/99IdvVkTULwTcxrxhF84Ew">Spring 源码学习 13：initMessageSource</a></li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2021/01/17/source-spring-16.html">https://liuzhihang.com/2021/01/17/source-spring-16.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Spring/">Spring</a><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/fybVmp-2dcCmU.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2021/01/23/source-spring-circular-dependence-1.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/1QnEIw-1agsnx.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Spring 是如何解决循环依赖的？</div></div></a></div><div class="next-post pull-right"><a href="/2021/01/12/source-spring-15.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/II1QBD-L3tiN3.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Spring 源码学习 15：finishBeanFactoryInitialization（重点）</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/12/28/source-spring-11.html" title="Spring 源码学习 11：invokeBeanFactoryPostProcessors"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/hoPCO0-yAfXNu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">Spring 源码学习 11：invokeBeanFactoryPostProcessors</div></div></a></div><div><a href="/2020/12/27/source-spring-10.html" title="Spring 源码学习 10：prepareBeanFactory 和 postProcessBeanFactory"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/nDmWFO-dHVLOp.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-27</div><div class="title">Spring 源码学习 10：prepareBeanFactory 和 postProcessBeanFactory</div></div></a></div><div><a href="/2021/01/01/source-spring-12.html" title="Spring 源码学习 12：registerBeanPostProcessors"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/dHDiOq-CxKXF8.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-01-01</div><div class="title">Spring 源码学习 12：registerBeanPostProcessors</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#getSingleton"><span class="toc-text">getSingleton</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E4%BB%8E%E7%BC%93%E5%AD%98%E4%B8%AD%E8%8E%B7%E5%8F%96-singletonObjects"><span class="toc-text">1. 从缓存中获取 singletonObjects</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E5%88%9B%E5%BB%BA-singletonObject"><span class="toc-text">2. 创建 singletonObject</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E5%B0%86%E5%88%9B%E5%BB%BA%E7%9A%84-singletonObject-%E6%B7%BB%E5%8A%A0%E5%88%B0%E7%BC%93%E5%AD%98%E4%B8%AD"><span class="toc-text">3. 将创建的 singletonObject 添加到缓存中</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#createBean"><span class="toc-text">createBean</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#doCreateBean"><span class="toc-text">doCreateBean</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#getObjectForBeanInstance"><span class="toc-text">getObjectForBeanInstance</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E7%9B%B8%E5%85%B3%E6%8E%A8%E8%8D%90"><span class="toc-text">相关推荐</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: 'e53c368bcda442367218377032771fa6',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>